﻿// Less2DB.NET framework
// http://code.google.com/p/less2db/
//
// Copyright © Wangzhongwu, 2011
// alex.wzw@gmail.com
//

namespace Less2DB.SQLBuilder
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// 表示 SQL INSERT 查询构造器。
    /// </summary>
    class SQLInsertBuilder : BuilderBase
    {
        public SQLInsertBuilder(string tableName, string[] fields)
        {
            this.TableName = tableName;
            this.Fields = fields;
        }

        private string ToString(string table, string fields, string values)
        {
            string querystring = "INSERT INTO {TABLE} ({FIELDS}) VALUES ({VALUES})";

            querystring = querystring.Replace("{TABLE}", table);
            querystring = querystring.Replace("{FIELDS}", fields);
            querystring = querystring.Replace("{VALUES}", values);

            return querystring;
        }

        /// <summary>
        /// 将此实例的值转换为 System.String。
        /// </summary>
        /// <returns>其值与此实例相同的字符串。</returns>
        public override string ToString()
        {
            var sbFields = new StringBuilder();
            var sbValues = new StringBuilder();

            foreach (string field in this.Fields)
            {
                if (sbFields.Length == 0)
                {
                    sbFields.Append(field);
                    sbValues.Append("@" + field);
                }
                else
                {
                    sbFields.Append(", " + field);
                    sbValues.Append(", @" + field);
                }
            }

            string fields = sbFields.ToString();
            string values = sbValues.ToString();

            return this.ToString(this.TableName, fields, values);
        }
    }
}
